<?php

namespace App\Http\Models;

use App\Admin\Models\Notice;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    // 用户的文章列表
    public function posts()
    {
        return $this->hasMany(Post::class, 'user_id', 'id');
    }

    // 关注我的粉丝 [以star_id身份去获取关联数据]
    public function fans()
    {
        return $this->hasMany(Fan::class, 'star_id', 'id');
    }
    
    // 我关注的明星 [以fan_id身份去获取关联数据]
    public function stars()
    {
        return $this->hasMany(Fan::class, 'fan_id', 'id');
    }

    // 执行关注 [user_id增加(当前用户)粉丝,user关注了user_id,user增加了明星(user_id)]
    public function doFan($user_id)
    {
        $fan = new Fan();
        $fan->star_id = $user_id;
        $this->stars()->save($fan); // 自动存关联键[id=>fan_id]
    }

    // 执行取消关注 [user删除了明星(user_id)]
    public function doUnFan($user_id)
    {
        $fan = new Fan();
        $fan->star_id = $user_id;
        $this->stars()->delete($fan); // 自动存关联键[id=>fan_id]
    }

    // 当前用户是否被user_id关注了
    public function hasFan($user_id)
    {
        return $this->fans()->where('fan_id', $user_id)->count() ? true : false;
    }

    // 当前用户是否关注了user_id
    public function hasStar($user_id)
    {
        return $this->stars()->where('star_id', $user_id)->count() ? true : false;
    }

    // 获取用户的通知
    public function notices()
    {
        return $this->belongsToMany(Notice::class, 'notice_users', 'user_id', 'notice_id')->withPivot(['user_id', 'notice_id']);
    }

    // 给用户增加通知
    public function addNotice(Notice $notice)
    {
        return $this->notices()->save($notice);
    }
}
